package com.bw.wxy.factroy.interceptor;

import android.util.Log;

import com.bw.wxy.common.LogUtils;
import com.bw.wxy.common.MD5Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class SignInterceptor implements Interceptor {
    private static final String TAG = "SignInterceptor";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldrequest = chain.request();
        Log.i(TAG, "oldrequest: "+oldrequest);
        Request.Builder builder = new Request.Builder();
        builder.url(oldrequest.url());
        builder.headers(oldrequest.headers());
        Log.i(TAG, "oldrequest.headers(): "+oldrequest.headers());
        RequestBody oldbody = oldrequest.body();
//        com.blankj.utilcode.util.LogUtils.json(oldbody);
        Buffer buffer = new Buffer();
        oldbody.writeTo(buffer);
        String oldJson="";
        byte[] buff=new byte[1024];
        while (buffer.read(buff)!=-1){
            oldJson+=new String(buff);
        }
        Log.i(TAG, "oldJson: "+oldJson);
        buffer.clear();
        oldJson.trim();
        LogUtils.e(oldJson);

        String value="";
        String json="";

        try {
            JSONObject jsonObject = new JSONObject(oldJson);
            com.blankj.utilcode.util.LogUtils.json(jsonObject);
            Log.i(TAG, "jsonObject: "+jsonObject);
            Iterator<String> keys = jsonObject.keys();//获取全部json中的key
            while (keys.hasNext()){
                value+=jsonObject.getString(keys.next());
            }
            Log.i(TAG, "value: "+value);
            String sign = MD5Utils.createSign(value);
            jsonObject.put("sign",sign);
            json=jsonObject.toString();
            com.blankj.utilcode.util.LogUtils.json(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        LogUtils.e(json);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
        com.blankj.utilcode.util.LogUtils.json(requestBody);
        builder.post(requestBody);
        return chain.proceed(builder.build());
    }
}

